<!--
* description: 质量跟踪特殊件查询
* author: xuliwen
* createdDate: 2021-01-21
-->
<template>
  <div class="app-container app-container-table">
    <one-table-template
      ref="multipleTable"
      :key="oneTableKey"
      :dynamic-buttons="tableButtons"
      :dynamic-components="tableComponents"
      :dynamic-api-config="apiConfig"
      :dynamic-table-cols="tableCols"
      :dynamic-form-fields="formField"
      :dynamic-is-show-select="false"
      :dynamic-is-init-table="true"
      :dynamic-api-style="'restful'"
    />

    <edit
      :key="editPopupsKey"
      :dynamic-edit-row-data="editRowData"
      :popups-visible="editPopupsVisible"
      :popups-state="editPopupsState"
      :dynamic-api-style="'restful'"
      @close="close"
    />
  </div>
</template>
<script>

import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
import OneTableTemplate from '@/components/templates/oneTable'
import api from '@/api/se/apiBaseData'
import Vue from 'vue'

export default {
  name: 'qualitySpecialPartsQuery',

  components: {
    OneTableTemplate,
    Edit: () => import('./edit')
  },
  // 组件混入对象
  mixins: [oneTableWithViewTemplateMixins],

  // 阻塞路由预加载网格中组件的数据
  beforeRouteEnter(to, from, next) {
    Vue.prototype.$ConfigCache.CacheConfig.initData([to.path, ''], function() {
      next()
    })
  },

  data() {
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path

    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])

    return {
      editRowData: {},
      // 网格查询API配置对象
       // api配置
        apiConfig: api.qualitySpecialPartsQuery,
      // 动态组件-按钮
      tableButtons: [
        {
          compKey: 'btnKey1',
          type: 'primary',
          size: 'small',
          name: 'search',
          clickEvent: () => this.queryTable(1),
          text: this.$t('sys.button.query'), // 查询
          position: 'right',
          fuzzySearch: true
        },
        {
          compKey: 'btnKey2',
          type: '',
          size: 'small',
          name: 'reset',
          clickEvent: () => this.reset(),
          text: this.$t('sys.button.reset'),
          position: 'right' // 重置
        },
        {
          compKey: 'btnKey3',
          type: '',
          size: 'small',
          name: 'add',
          clickEvent: this.add,
          text: this.$t('sys.button.add'), // 新增
          position: 'left'
        },
         {
            compKey: 'btnKey4',
            type: '',
            size: 'small',
            name: 'importTemplate',
            position: 'upload',
             clickEvent: () => this.handFileListChange(),
            text: '导入'
          },
        {
            compKey: 'btnKey5',
            type: 'text',
            size: 'small',
            name: '',
            position: 'upload',
            click: (event) => {this.templateDownload()
              // this.export(
              //   // api.templateDownload.APIUrl,
              //   '质量跟踪特殊件查询模板',
              //   { dataType: 'excel' }
              // )
            }
          },
      ],

      // 动态组件-查询条件
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
            .tableComponents
          : [
            {
              compKey: 'compKey1',
              labelName: '备件编码：',
              codeField: 'partNo',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey2',
              labelName: '备件名称：',
              codeField: 'partName',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true
            },   
            {
                compKey: "compKey3",
                labelName: "状态",
                codeField: "isEnable",
                component: () => import("@/components/org/LookupValue"),
                oFields: "statusId,statusText",
                options: [
                  { statusId: "1", statusText: "启用" },
                  { statusId: "0", statusText: "禁用" },
                ],
                type: "dropdownList",
                isMul: false,
                isMust: true,
              },
          ],

      // 动态生成网格列
      tableCols:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          : [
            {
              prop: 'releaseId',
              label: '主键ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'updateControlId',
              label: '并发控制ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'controlBtn1',
              label: '操作',
              minWidth: 180,
               isComponent: true,
                comps: [
                  {
                    compKey: "propKey1",
                    labelName: "启用",
                    rowFileds: "show:isEnable-0",
                    clickEvent: (index) => this.delet(index),
                    component: () => import("@/components/org/linkButton"),
                    align: "center",
                  },
                  {
                    compKey: "propKey1",
                    labelName: "禁用",
                    rowFileds: "show:isEnable-1",
                    clickEvent: (index) => this.delet(index),
                    component: () => import("@/components/org/linkButton"),
                    align: "center",
                  },
                ],
            },
            {
              prop: 'bigAreaId',
              label: '大区ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'partNo',
              label: '备件编码'
            },
            {
              prop: 'partName',
              label: '备件名称'
            },
            {
              prop: 'isEnableCn',
              label: '状态'
            },          
            {
              prop: 'creator',
              label: '创建人'
            },
            {
              prop: 'createdDate',
              label: '创建时间'
            },
            {
              prop: 'modifier',
              label: '更新人'
            },
            // {
            //   prop: 'remark',
            //   label: '备注'
            // },
            {
              prop: 'lastUpdateDate',
              label: '最后更新时间'
            },
          ],

      // 表单查询数据
      formField: this.$utils.getFormField(this, {
        partNo: '',
        partName: '',
        isEnable: '',
      }, this.$ConfigCache.CacheConfig.cacheData[viewPageCode])
    }
  },

  mounted() {
    // 列表查询
    this.queryTable(1)
  },

  methods: {
      templateDownload(){
      const fileName = this.$utils.fileNameWithTime('质量跟踪特殊件模板.xlsx')
      this.$requestAPI({
        apiUrl:api.qualitySpecialPartsDownload.APIUrl,
        variables: { dataType: 'excel' }
      }).then(res => {
        this.$utils.downloadFile(res, fileName)
      }).catch(err => {
        console.log(err)
      })
    },
    handFileListChange(file, fileList) {
       if(this.beforeAvatarUpload(file)){
         this.handleChange(file)
       }
     },
        beforeAvatarUpload(file) {
      if (file.size > 50 * 1024 * 1024) {
        this.$message({
          message: "文件大小不能超过50M",
          type: "warning"
        });
        return false;
      }
      let fileType = file.name.substr(file.name.lastIndexOf(".") + 1);
      if (fileType != "xls" && fileType != "xlsx") {
        this.$message({
          message: "只能导入后缀为xls,xlsx的文件！",
          type: "warning"
        });
        return false;
      }
      return true;
    },
     handleChange(param) {
      const loading = this.$loading({
        lock: true,
        text: "导入中...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      const that = this;
      const url =api.qualitySpecialPartsImport.APIUrl;
      that
        .$requestUpload(url, param)
        .then(response => {
          loading.close();
          if (response.result === "1") {
            this.$message({
              message: "导入成功",
              type: "success"
            });
            that.queryTable();
          } else {
            this.$message({
              message: response.msg,
              type: "warning"
            });
          }
        })
        .catch(err => {});
    },
    delet(index){
       this.editRowData =this.$refs['multipleTable'].list[index]
       const that = this;
      const queryObj = {
        // 保存mutation
        type: "mutation",
        // api配置
        apiConfig: api.qualitySpecialPartsDelQuality,
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: this.editRowData,
      };
      // 转换了中台请求格式数据
      var paramD = this.$getParams(queryObj);
      // 调用中台API方法（可复用）
      this.$requestAPI(paramD).then((response) => {
        if (response.result === "1") {
          this.$message({
            message: response.msg /* 删除成功*/,
            type: "success",
            duration: 1000,
          });
           this.queryTable(1);
        } else {
          // 保存失败
          this.$message({
            message:response.msg,
            type: "warn",
            uration: 1000,
          });
        }
      });
    }
  }
}
</script>
